﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data;
using SmartMD.DataAccess.Oracle;
using System.Collections.ObjectModel;
using SmartMD.Manager.Specimens;
using SmartMD.Manager.Utils;
using SmartMD.DataModel.Entity;
using SmartMD.DataAccess.Service;
using Duoease.ContainerModel;
using Duoease.ContainerModel.Utils;

namespace SmartMD.Manager.Container
{
    /// <summary>
    /// SpecimenMsg.xaml 的交互逻辑
    /// </summary>
    public partial class SpecimenMsg : Window
    {
        public event RoutedEventHandler SaveModelClick;
        public ContainerModelEntity CME = null;
        public bool IsShow = true;

        public SpecimenMsg(SpecimenStyle style, ContainerModelView cm,ContainerModelEntity cme)
        {
            InitializeComponent();

            CM = cm;
            CME = cme;
            switch (style)
            {
                case SpecimenStyle.GetMsg:
                    this.Title = "查看标本";
                    this.textBoxSName.IsReadOnly = true;
                    this.textBoxID.IsReadOnly = true;
                    this.textBoxPName.IsReadOnly = true;
                    this.textBoxStyle.IsReadOnly = true;
                    this.textBoxCName.IsReadOnly = true;
                    this.textBoxTime.IsReadOnly = true;
                    this.textBoxP.IsReadOnly = true;
                    BtnOK.Content = "关闭";
                    BtnOK.Click+=new RoutedEventHandler(BtnClose_Click);
                    GetMsg();
                    break;
                case SpecimenStyle.InputMsg:
                    this.Title = "存入标本";
                    this.textBoxID.Text = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString();
                    BtnOK.Content = "保存";
                    BtnOK.Click += new RoutedEventHandler(BtnSave_Click);
                    break;
                case SpecimenStyle.RemoveMsg:
                    this.Title = "取出标本";
                    this.textBoxSName.IsReadOnly = true;
                    this.textBoxID.IsReadOnly = true;
                    this.textBoxPName.IsReadOnly = true;
                    this.textBoxStyle.IsReadOnly = true;
                    this.textBoxCName.IsReadOnly = true;
                    this.textBoxTime.IsReadOnly = true;
                    this.textBoxP.IsReadOnly = true;
                    BtnOK.Content = "取出";
                    BtnOK.Click += new RoutedEventHandler(BtnRemove_Click);
                    GetMsg();
                    break;
            }
        }

        public enum SpecimenStyle
        {
            InputMsg,//载入标本
            GetMsg,//查看标本
            RemoveMsg//取出标本
        }

        /// <summary>
        /// 标本所在盒子
        /// </summary>
        private ContainerModelView _CM = null;
        public ContainerModelView CM
        {
            get { return _CM; }
            set 
            {
                _CM = value;
                if (_CM != null)
                {
                    Position = CM.BoxModel.ID + "-" + ModelUtil.GetLetter(CM.MouseRow) + CM.MouseColumn.ToString();
                    this.textBoxPosition.Text = Position;
                    row = CM.MouseRow-1;
                    column = CM.MouseColumn-1;
                }
            }
        }

        /// <summary>
        /// 标本位置
        /// </summary>
        private string _Position = "";
        public string Position
        {
            get { return _Position; }
            set { _Position = value; }
        }

        /// <summary>
        /// 标本位置
        /// </summary>
        private string _PatientName = "";
        public string PatientName 
        {
            get { return _PatientName; }
            set { _PatientName = value; this.textBoxPName.Text = _PatientName; }
        }

        /// <summary>
        /// 标本所在行
        /// </summary>
        private int _row = 0;
        public int row
        {
            get { return _row; }
            set { _row = value; }
        }

        /// <summary>
        /// 标本所作列
        /// </summary>
        private int _column = 0;
        public int column
        {
            get { return _column; }
            set { _column = value; }
        }

        private void BtnSave_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //保存标本信息
                if (this.textBoxID.Text.Trim() == "")
                {
                    MessageBox.Show("请确定标本标识不为空！", "提示", MessageBoxButton.OK);
                    return;
                }
                if (this.textBoxSName.Text.Trim() == "")
                {
                    MessageBox.Show("请确定标本名称不为空！", "提示", MessageBoxButton.OK);
                    return;
                }

                string PatientName = "";
                StringBuilder sb = new StringBuilder();
                sb.Clear();
                sb.Append("select PATIENTID from  DUO_PATIENT where NAME='" + this.textBoxPName.Text.Trim() + "'");
                DataTable dt = ConnectDatabase.getInstance().Select(sb.ToString());
                if (dt != null && dt.Rows.Count > 0)
                {
                    PatientName = dt.Rows[0][0].ToString();
                }
                if (PatientName=="")
                {
                    MessageBox.Show("没有该病人！", "提示", MessageBoxButton.OK);
                    return;
                }
                sb.Clear();
                sb.Append("insert into DUO_SPECIMENS (SPECID, NAME, PATIENTID, RECORDID, FOLLOWUPTIMES, FOLLOWUPDATE, COLLECTER, SPECSTATUS, SPECNUM, SPECTYPE, FREEZETHRAWTIMES, SUBJECT) values");
                sb.Append("('"+this.textBoxID.Text.Trim()+"', '"+this.textBoxSName.Text.Trim()+"','");
                sb.Append(PatientName + "', '','");
                sb.Append("', to_timestamp('" + this.textBoxTime.Text.Trim() + "','yyyy-mm-dd hh24:mi:ss.ff'),'");
                sb.Append(this.textBoxCName.Text.Trim() + "', '','");
                sb.Append("1" + "', '" + this.textBoxStyle.Text.Trim() + "','");
                sb.Append("', '')");
                dt = ConnectDatabase.getInstance().Select(sb.ToString());
                //if (dt == null || dt.Rows.Count <= 0)
                //{
                //    MessageBox.Show("标本存入错误", "提示", MessageBoxButton.OK);
                //    return;
                //}

                sb.Clear();
                sb.Append("insert into DUO_SPEC_CONTAINER_MAPPING (ID, CONTAINERID, SPECID) values");
                sb.Append("('" + System.Guid.NewGuid().ToString() + "', '" + this.textBoxPosition.Text.Trim() + "','");
                sb.Append(this.textBoxID.Text.Trim() + "')");
                dt = ConnectDatabase.getInstance().Select(sb.ToString());
                
                sb.Clear();
                sb.Append("select * from  DUO_CONTAINER  where SITECODE='" + this.textBoxPosition.Text.Trim() + "'");
                dt = ConnectDatabase.getInstance().Select(sb.ToString());
                if (dt.Rows.Count > 0 && dt != null)
                {
                    sb.Clear();
                    sb.Append("update DUO_CONTAINER set ISSTORED = 'True', STOREDDATE='" + DateTime.Now.ToFileTime().ToString());
                    sb.Append("' where SITECODE='" + this.textBoxPosition.Text.Trim() + "'");
                    dt = ConnectDatabase.getInstance().Select(sb.ToString());
                }
                else
                {
                    sb.Clear();
                    sb.Append("insert into DUO_CONTAINER (CONTAINERID,SITECODE,MODELTYPE,REMAININGCAPACITY,WHOLECAPACITY,DESCRIPTION,METATYPE,ISSTORED,STOREDDATE) values");
                    sb.Append("('" + this.textBoxID.Text.Trim() + "', '" + this.textBoxPosition.Text.Trim() + "','','1','1','','','True',");
                    sb.Append("to_timestamp('" + DateTime.Now + "','yyyy-mm-dd hh24:mi:ss.ff'))");
                    dt = ConnectDatabase.getInstance().Select(sb.ToString());

                }
               // CM.SetModelPercent(CM.BoxModel.ID, CM.ShelfModel.ID, row, column, true);

                ////盒子存入状态
                //bool[,] IsFull = CM.BoxIsFull;
                //IsFull[row, column] = true;
                //CM.BoxIsFull = IsFull;
              
                ////架子存储状态
                //string[] str = CM.BoxModel.ID.Split('-');
                //int r = Convert.ToInt32(str[2]) / 10-1;
                //int c = Convert.ToInt32(str[2]) % 10-1;
                //double[,] FullPercent = CM.DrawerFullPercent;
                //FullPercent[r, c] += (double)1 / (CM.BoxModel.Row * CM.BoxModel.Column);
                //CM.DrawerFullPercent = FullPercent;

                //冰箱存储状态               
                //r = Convert.ToInt32(str[1]) / 10-1;
                //c = Convert.ToInt32(str[1]) % 10-1;
                //FullPercent = CM.IceFullPercent;
                //FullPercent[r, c] += (double)1 / (CM.BoxModel.Row * CM.BoxModel.Column);
                //CM.IceFullPercent = FullPercent;
                if (CME == null)
                {
                    SaveModelClick(sender, e);
                }
                else
                {
                    EditModel();
                }
                MessageBox.Show("标本存入成功！", "提示", MessageBoxButton.OK);
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("标本存入失败，"+ex.Message, "提示", MessageBoxButton.OK);
                this.Close();
            }
        }

        private void BtnClose_Click(object sender, RoutedEventArgs e)
        {            
            this.Close();
        }

        private void BtnRemove_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //取出标本信息
                if (this.textBoxID.Text.Trim() == "" || this.textBoxSName.Text.Trim() == "")
                {
                    MessageBox.Show("盒子内无标本！", "提示", MessageBoxButton.OK);
                    IsShow = false;
                    this.Close();
                    return;
                }

                StringBuilder sb = new StringBuilder();
                sb.Clear();
                sb.Append("delete from DUO_SPECIMENS where SPECID = '" + this.textBoxPosition.Text.Trim() + "'");
                DataTable dt = ConnectDatabase.getInstance().Select(sb.ToString());

                sb.Clear();
                sb.Append("delete from DUO_SPEC_CONTAINER_MAPPING where SPECID = '" + this.textBoxPosition.Text.Trim() + "'");
                dt = ConnectDatabase.getInstance().Select(sb.ToString());

                sb.Clear();
                sb.Append("update DUO_CONTAINER set ISSTORED = 'False' where SITECODE='" + this.textBoxPosition.Text.Trim() + "'");
                dt = ConnectDatabase.getInstance().Select(sb.ToString());

               // CM.SetModelPercent(CM.BoxModel.ID, CM.ShelfModel.ID, row, column, false);

                ////取出状态
                //bool[,] IsFull = CM.BoxIsFull;
                //IsFull[row, column] = false;
                //CM.BoxIsFull = IsFull;

                ////架子存储状态
                //string[] str = CM.BoxModel.ID.Split('-');
                //int r = Convert.ToInt32(str[2]) / 10-1;
                //int c = Convert.ToInt32(str[2]) % 10-1;
                //double[,] FullPercent = CM.DrawerFullPercent;
                //FullPercent[r, c] -= (double)1 /(CM.BoxModel.Row * CM.BoxModel.Column);
                //CM.DrawerFullPercent = FullPercent;

                //冰箱存储状态               
                //r = Convert.ToInt32(str[1]) / 10-1;
                //c = Convert.ToInt32(str[1]) % 10-1;
                //FullPercent = CM.IceFullPercent;
                //FullPercent[r, c] -= (double)1 / (CM.BoxModel.Row * CM.BoxModel.Column);
                //CM.IceFullPercent = FullPercent;
                if (CME == null)
                {
                    SaveModelClick(sender, e);
                }
                else
                {
                    EditModel();
                }
                MessageBox.Show("标本已经取出！", "提示", MessageBoxButton.OK);
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("标本取出失败，" + ex.Message, "提示", MessageBoxButton.OK);
                this.Close();
            }
        }

        private void GetMsg()
        {
            try
            {
                if (Position == "")
                {
                    MessageBox.Show("没有位置信息，请点击需要查询的盒子", "提示", MessageBoxButton.OK);
                    IsShow = false;
                    this.Close();
                    return;
                }
                StringBuilder sb = new StringBuilder();
                sb.Clear();
                sb.Append("select t.NAME,t.SPECID,t2.NAME as PATIENTNAME, t.SPECTYPE, t2.DIAGNOSE,t.FOLLOWUPDATE,t.COLLECTER");
                sb.Append(" from DUO_SPECIMENS t, DUO_PATIENT t2, DUO_SPEC_CONTAINER_MAPPING t4, DUO_CONTAINER t3");
                sb.Append(" where t4.SPECID = t.SPECID");
                sb.Append(" and t.PATIENTID = t2.PATIENTID and t3.SITECODE=t4.CONTAINERID and t3.ISSTORED = 'True'");
                sb.Append(" and t3.SITECODE = '" + Position + "'");//根据位置查询标本信息

                DataTable dt = ConnectDatabase.getInstance().Select(sb.ToString());
              
                if (dt != null && dt.Rows.Count > 0)
                {
                    this.textBoxSName.Text = dt.Rows[0][0].ToString();
                    this.textBoxID.Text = dt.Rows[0][1].ToString();
                    this.textBoxPName.Text = dt.Rows[0][2].ToString();
                    this.textBoxStyle.Text = dt.Rows[0][3].ToString();
                    this.textBoxP.Text = dt.Rows[0][4].ToString();
                    this.textBoxTime.Text = dt.Rows[0][5].ToString();
                    this.textBoxCName.Text = dt.Rows[0][6].ToString();
                }
                else
                {
                    MessageBox.Show("盒子内无标本！", "提示", MessageBoxButton.OK);
                    IsShow = false;
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("查询失败！" + ex.Message, "提示", MessageBoxButton.OK);
                IsShow = false;
                this.Close();
            }
        }

        private void InsertMsg()
        {
            try
            {
                if (this.textBoxID.Text.Trim() == "")
                {
                    MessageBox.Show("请输入标本编号！", "提示", MessageBoxButton.OK);             
                    return;
                }
                StringBuilder sb = new StringBuilder();
                sb.Clear();
                sb.Append("select t.SPECID,t2.NAME as PATIENTNAME, t.SPECTYPE, t2.DIAGNOSE,t.FOLLOWUPDATE,t.COLLECTER");
                sb.Append(" from DUO_SPECIMENS t, DUO_PATIENT t2, DUO_SPEC_CONTAINER_MAPPING t4, DUO_CONTAINER t3");
                sb.Append(" where t4.SPECID = t.SPECID");
                sb.Append(" and t.PATIENTID = t2.PATIENTID");
                sb.Append(" and t3.SITECODE = '" + Position + "'");//根据位置查询标本信息

                DataTable dt = ConnectDatabase.getInstance().Select(sb.ToString());

                if (dt != null && dt.Rows.Count > 0)
                {
                    this.textBoxID.Text = dt.Rows[0][0].ToString();
                    this.textBoxPName.Text = dt.Rows[0][1].ToString();
                    this.textBoxStyle.Text = dt.Rows[0][2].ToString();
                    this.textBoxP.Text = dt.Rows[0][3].ToString();
                    this.textBoxTime.Text = dt.Rows[0][4].ToString();
                    this.textBoxCName.Text = dt.Rows[0][5].ToString();
                }
                else
                {
                    MessageBox.Show("查询失败，未查到您所查询的标本！", "提示", MessageBoxButton.OK);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("查询失败！" + ex.Message, "提示", MessageBoxButton.OK);
            }
        }

        private bool EditModel()
        {
            if (CME == null)
            {
                return false;
            }

            bool success = false;           
            string styleXml = this.CM.docmodel.Xml.InnerXml.ToString();
            CME.StyleFile = CompressionHelper.CompressToByte(styleXml);
            success = DataServiceManager.ContainerModelService.SaveContainerModel(CME);
            return success;
        }

        private void textBoxTime_MouseDown(object sender, MouseButtonEventArgs e)
        {
            calendar1.Visibility = Visibility.Visible;
        }

        private void calendar1_SelectedDatesChanged(object sender, SelectionChangedEventArgs e)
        {
            textBoxTime.Text = calendar1.SelectedDate.Value.ToString();
            calendar1.Visibility = Visibility.Hidden;
        }

        private void calendar1_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            calendar1.Visibility = Visibility.Hidden;
        }

        //打开病人列表
        private PatientSearchResult patientSearchRslt = null;        
        private void SearchPatient_Click(object sender, RoutedEventArgs e)
        {
            patientSearchRslt = new PatientSearchResult(this);
            
            ObservableCollection<PatientInfo> patientInfoList = DataServiceManager.PatientInfoService.loadAllPatientInfos();
            for (int i = 0; i < patientInfoList.Count; i++)
            {
                patientSearchRslt.PatientInfoList.Add(patientInfoList[i]);
            }
            patientSearchRslt.Topmost = true;
            patientSearchRslt.ShowDialog();
        }
    }
}
